package zhan;

import zhan.Stack;

import java.util.Scanner;
//用栈进行进制相互转换
public class Domo {
    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);
        Stack s = new Stack(100);
        while(true)
        {
            System.out.print("请输入要输入数字的进制(2 8 10 16):");
            int jin = input.nextInt();
            if(jin == 2||jin == 8||jin == 10||jin == 16)
            {

                System.out.print("请输入数字: ");

                String str = input.next();
                int result = choice(str,jin);
                System.out.print("请输入要转为的进制(2 8 10 16):");
                int zhuan = input.nextInt();
                if(zhuan == 2||zhuan == 8||zhuan == 10||zhuan == 16){
                    while(result != 0)
                    {
                        int temp = result % zhuan;
                        s.push(temp);
                        result /= zhuan;
                    }
                    System.out.print("结果为: ");
                    while(!s.isEmpty())
                    {
                        int temp = s.pop();
                        if(temp >= 0 && temp <= 9)
                        {
                            System.out.print(" " + (char)(temp + '0'));
                        }
                        else
                        {
                            System.out.print(" " + (char)(temp - 10 + 'A'));
                        }
                    }
                    System.out.println();
                }
                else{
                    System.out.println("无法转换为该进制");
                    System.exit(0);
                }

            }
            else{
                System.out.println("无法转换该进制");
                System.exit(0);
            }
        }

    }
    //转换成10进制
    public static int choice(String temp,int jin)
    {
        int sum = 0;
        int top = 0;
        for(int i = temp.length() - 1;i >= 0;i --)
        {

            char ch = temp.charAt(i);

            if(ch >= '0' && ch <= '9')
            {
                sum += Math.pow(jin,top) * (ch - '0');
                top ++;
            }
            else
            {
                sum += Math.pow(jin,top) * (ch - '7');
                top ++;
            }
        }
        return sum;
    }
}